"""
Case Type   : 共享存储-工具-系统内部工具-pg_resetxlog
Case Name   : 共享存储模式下，数据库在运行状态，执行pg_resetxlog命令
Create At   : 2023/4/25
Owner       : opentestcase019
Description :
    1.查看数据库状态，确保数据库为开启状态
    2.执行pg_resetxlog命令;
Expect      :
    1.成功
    2.执行失败，提示信息为pid文件已存在
History     :
"""
import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class ShareStorageTool(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.primary_node = Node('PrimaryDbUser')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.common = Common()
        self.constant = Constant()
        self.node_num = self.primary_sh.get_node_num()

    def test_sharestorage_tool(self):
        step1 = "-----step1:查看数据库状态，确保数据库为开启状态;expect:成功-----"
        self.logger.info(step1)
        start_msg = self.primary_sh.exec_cm_ctl(mode='start')
        self.logger.info(start_msg)
        self.assertIn(self.constant.cm_start_success_msg,
                      start_msg, '启动集群失败')
        time.sleep(30)
        status = self.primary_sh.exec_cm_ctl(mode='query', param='-Civdp')
        self.logger.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败')

        step2 = "-----step2:执行pg_resetxlog命令;expect:执行失败，提示信息为pid文件已存在-----"
        self.logger.info(step2)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
            f"pg_resetxlog {macro.DB_INSTANCE_PATH} --enable-dss " \
            f"--socketpath={macro.UDS_PATH} --vgname=+data"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        self.assertIn('pg_resetxlog: lock file "postmaster.pid" exists',
                      execute_msg, "执行失败" + step2)

    def tearDown(self):
        self.logger.info("-----无需清理环境-----")
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
